package top.heue.temp.util.permission

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import top.heue.temp.app.T
import java.util.*

class PermissionUtil(private val context: Context) {

    private val allPermissions by lazy {
        val p = context.packageManager
        val permissions = p.getPackageInfo(
            context.packageName,
            PackageManager.GET_PERMISSIONS
        ).requestedPermissions
        permissions
    }

    val permissions by lazy {
        val all = allPermissions.toMutableList()
        if (!all.contains(Permission.MANAGE_EXTERNAL_STORAGE)) return@lazy all
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            all.remove(Permission.READ_EXTERNAL_STORAGE)
            all.remove(Permission.WRITE_EXTERNAL_STORAGE)
        } else {
            all.remove(Permission.MANAGE_EXTERNAL_STORAGE)
        }
        all
    }

    val isGranted: Boolean get() = XXPermissions.isGranted(context, permissions)
    val denied get() = XXPermissions.getDenied(context, permissions)

    val isPowerIgnore by lazy {
        val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            powerManager.isIgnoringBatteryOptimizations(context.packageName)
        } else {
            false
        }
    }

    @SuppressLint("BatteryLife")
    fun powerIgnoreReply() = context.run {
        if (!isPowerIgnore) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val i = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                i.data = Uri.parse("package:$packageName")
                startActivity(i)
            } else {
                toSelfSetting()
                T.show("系统版本不支持跳转，将进入应用详情页")
            }
        }
    }


    /**
     * 跳转到应用详情页
     */
    fun toSelfSetting() {
        val i = getAutostartSettingIntent()
        context.startActivity(i)
    }

    /**
     * 自启intent生成
     */
    private fun getAutostartSettingIntent(): Intent {
        var componentName: ComponentName? = null
        val brand: String = Build.MANUFACTURER
        val intent = Intent()
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        when (brand.lowercase(Locale.getDefault())) {
            "samsung" -> componentName = ComponentName(
                "com.samsung.android.sm",
                "com.samsung.android.sm.app.dashboard.SmartManagerDashBoardActivity"
            )

            "huawei" ->             //荣耀V8，EMUI 8.0.0，Android 8.0上，以下两者效果一样
                componentName = ComponentName(
                    "com.huawei.systemmanager",
                    "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity"
                )

            "xiaomi" -> componentName = ComponentName(
                "com.miui.securitycenter",
                "com.miui.permcenter.autostart.AutoStartManagementActivity"
            )

            "vivo" -> //            componentName = new ComponentName("com.iqoo.secure", "com.iqoo.secure.safaguard.PurviewTabActivity");
                componentName = ComponentName(
                    "com.iqoo.secure",
                    "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"
                )

            "oppo" -> //            componentName = new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity");
                componentName = ComponentName(
                    "com.coloros.oppoguardelf",
                    "com.coloros.powermanager.fuelgaue.PowerUsageModelActivity"
                )

            "yulong", "360" -> componentName = ComponentName(
                "com.yulong.android.coolsafe",
                "com.yulong.android.coolsafe.ui.activity.autorun.AutoRunListActivity"
            )

            "meizu" -> componentName =
                ComponentName("com.meizu.safe", "com.meizu.safe.permission.SmartBGActivity")

            "oneplus" -> componentName = ComponentName(
                "com.oneplus.security",
                "com.oneplus.security.chainlaunch.view.ChainLaunchAppListActivity"
            )

            "letv" -> {
                intent.action = "com.letv.android.permissionautoboot"
                intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                intent.data = Uri.fromParts("package", context.packageName, null)
            }

            else -> {
                intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                intent.data = Uri.fromParts("package", context.packageName, null)
            }
        }
        intent.component = componentName
        return intent
    }
}